﻿using System;
using Foothill.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Foothill.DataAccess.Repository
{
    public class DbAccessBase
    {
        protected static Database FoothillDB;

        //static constructor
        static DbAccessBase()
        {
            FoothillDB = DatabaseFactory.CreateDatabase("FoothillDB");
        }

        public static void UseDatabase(DatabaseToUse dbType)
        {
            FoothillDB = DatabaseFactory.CreateDatabase(GetDatabaseName(dbType));
        }

        protected string GetDbString(Object obj, string defaultValue)
        {
            string retVal = obj as string;

            if (string.IsNullOrWhiteSpace(retVal))
            {
                return defaultValue;
            }

            return retVal;
        }

        protected int GetDbInt32( Object obj, int defaultValue )
        {
            return Convert.IsDBNull(obj) ? defaultValue : Convert.ToInt32(obj);
        }

        protected DateTime GetDbSmallDateTime(Object obj)
        {
            return Convert.IsDBNull( obj ) ? GlobalValues.SmallDateTime_MinValue : Convert.ToDateTime( obj );
        }

        protected bool GetDbBoolean(Object obj)
        {
            return Convert.IsDBNull(obj) ? false : Convert.ToBoolean(obj);
        }

        protected Guid GetDbGuid(object obj)
        {
            return Convert.IsDBNull(obj) ? Guid.Empty : (Guid)(obj);
        }

        public static DateTime ConvertToSmallDateTime(DateTime datetime)
        {
            if (datetime < DatabaseConstants.smalldatetimeMin || datetime > DatabaseConstants.smalldatetimeMax)
            {
                datetime = DatabaseConstants.smalldatetimeMin;
            }

            return datetime;
        }

        private static string GetDatabaseName(DatabaseToUse dbType)
        {
            string databaseName = "FoothillTestDB";

            switch (dbType)
            {
                case DatabaseToUse.Production:
                    databaseName = "FoothillDB";
                    break;
                case DatabaseToUse.Test:
                    databaseName = "FoothillTestDB";
                    break;
            }

            return databaseName;
        }
    }
}
